window.onload = function() {
    var stats = new Stats(),
        c = document.getElementById('c'),
        ctx = c.getContext('2d'),
        imgCloud = document.getElementById('cloud'),
        imgTree = document.getElementById('tree'),
        layers = [];

    window.addEventListener('resize', handleWindowResize, false);
    function handleWindowResize() {
        c.width = window.innerWidth * window.devicePixelRatio;
        c.height = window.innerHeight * window.devicePixelRatio;
    }
    handleWindowResize();

    /**
     * 图层类
     */
    function Layer(img, type, pxps, w, h) {
        if(!img) throw new Error('参数img必须');
        this.img = img;
        this.c = document.createElement('canvas');
        this.ctx = this.c.getContext('2d');
        this.offset = 0;
        this.pxPerS = pxps || 30;
        this.c.width = w || c.width;
        this.c.height = h || c.height;
        this.type = type || 'bg';
    }
    Layer.prototype.update = function(fps) {
        if(!fps && (fps = 60));
        var v = this.pxPerS / fps;
        this.offset += v;
        if(this.offset >= this.c.width) {
            this.offset = 0;
        }
        switch (this.type) {
            case 'bg': this.drawBackground(); break;
            case 'pt': this.drawPattern(); break;
            default: break;
        }
    }
    Layer.prototype.drawBackground = function() {
        this.ctx.save();
        this.ctx.translate(-this.offset, 0);
        this.ctx.drawImage(this.img, 0, 0, this.c.width, this.c.height);
        this.ctx.drawImage(this.img, this.c.width, 0, this.c.width, this.c.height);
        this.ctx.restore();
    }
    Layer.prototype.drawPattern = function() {
        this.ctx.clearRect(0, 0, this.c.width, this.c.height);
        this.ctx.save();
        var pa = this.ctx.createPattern(this.img, 'repeat-x');
        this.ctx.fillStyle = pa;
        this.ctx.translate(-this.offset, 0);
        this.ctx.fillRect(0, 0, this.c.width, this.c.height);
        this.ctx.fillRect(this.c.width, 0, this.c.width, this.c.height);
        this.ctx.restore();
    }

    layers.push(new Layer(imgCloud, 'bg'));
    layers.push(new Layer(imgTree, 'pt', 50, null, 400));

    (function loop() {
        ctx.clearRect(0, 0, c.width, c.height);
        requestAnimationFrame(loop);
        var fps = stats.update();
        for(var i = 0; i < layers.length; i += 1) {
            layers[i].update(fps);
            ctx.drawImage(layers[i].c, 0, 0);
        }
    })();
}